//
//  ShopScene.m
//  ProjectL
//
//  Created by Nguyen Tan Loc on 11/21/13.
//  Copyright (c) 2013 Nguyen Tan Loc. All rights reserved.
//

#import "ShopScene.h"
#import "ItemIcon.h"
#import "LevelManager.h"
#import "UserInfo.h"
#import "ItemInfo.h"
#import "MainGameScene.h"
#import "Utility.h"
#import "GameIAP.h"
#import "SimpleAudioEngine.h"

@implementation ShopScene

+(CCScene *) scene
{
    CCScene *scene = [CCScene node];
    ShopScene *layer = [ShopScene node];
    [scene addChild:layer];
    return scene;
}


-(id) init
{
    if (self = [super init])
    {
        [self initTwoLine];
        [self initItem];
        [self initMenu];
        [self initShop];
        [self updateUserInfo];
        [self updateLabelGold];
        
        mGoldShow = [UserInfo getInstance]._userGold;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateGoldNextGold) name:EVENT_GOLD_CHANGED object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateItemInfo) name:EVENT_ITEM_CHANGED object:nil];
    }
    return self;
}

-(void) initMenu
{
    CGSize winSize = [[CCDirector sharedDirector] winSize];
    
    mMenu = [[[CCMenu alloc] initWithArray:nil] autorelease];
    [mMenu setPosition:CGPointZero];
    [self addChild:mMenu];
    
//    mTabItem
    CCSprite *sprTabItem = [CCSprite spriteWithSpriteFrameName:SFN_SHOP_TAB_1];
    CCSprite *sprTabItemHover = [CCSprite spriteWithSpriteFrameName:SFN_SHOP_TAB_1];
    [sprTabItem setColor:CL_PANEL_BG];
    [sprTabItemHover setColor:CL_PANEL_BTN];
    mTabItem = [CCMenuItemSprite itemWithNormalSprite:sprTabItem selectedSprite:sprTabItemHover target:self selector:@selector(onTabItem)];
    [mTabItem setAnchorPoint:ccp(1.0f, 0.5f)];
    [mTabItem setPosition:uniPos(ccp(winSize.width / 2 - 0.5f, winSize.height / 2 + 150), ccp(winSize.width / 2 - 1, winSize.height / 2 + 300))];
    [mMenu addChild:mTabItem];
    
    
    CCSprite *sprTabGold = [CCSprite spriteWithSpriteFrameName:SFN_SHOP_TAB_1];
    CCSprite *sprTabGoldHover = [CCSprite spriteWithSpriteFrameName:SFN_SHOP_TAB_1];
    [sprTabGold setColor:CL_PANEL_BG];
    [sprTabGoldHover setColor:CL_PANEL_BTN];
    [sprTabGold setFlipX:YES];
    [sprTabGoldHover setFlipX:YES];
    mTabGold = [CCMenuItemSprite itemWithNormalSprite:sprTabGold selectedSprite:sprTabGoldHover target:self selector:@selector(onTabGold)];
    [mTabGold setAnchorPoint:ccp(0.0f, 0.5f)];
    [mTabGold setPosition:uniPos(ccp(winSize.width / 2 + 0.5f, winSize.height / 2 + 150), ccp(winSize.width / 2 + 1, winSize.height / 2 + 300))];
    [mMenu addChild:mTabGold];
    
    
    // active item tav
    [mTabItem selected];
    [mTabItem setIsEnabledWithoutUpdate:NO];
    
    
    // init icon
    CCSprite *iconItem = [CCSprite spriteWithSpriteFrameName:SFN_ICON_TIME];
    [iconItem setPosition:ccp(mTabItem.position.x - mTabItem.contentSize.width / 2, mTabItem.position.y)];
    [self addChild:iconItem];
    
    CCSprite *iconGold = [CCSprite spriteWithSpriteFrameName:SFN_ICON_GOLD];
    [iconGold setPosition:ccp(mTabGold.position.x + mTabGold.contentSize.width / 2, mTabGold.position.y)];
    [self addChild:iconGold];
    
    // icon and num gold
    mIconGold = [CCSprite spriteWithSpriteFrameName:SFN_ICON_GOLD];
    [mIconGold setPosition:uniPos(ccp(20, winSize.height - 20), ccp(40, winSize.height - 40))];
    [self addChild:mIconGold];
    
    mLabelGold = [[CCLabelBMFont alloc] initWithString:@"" fntFile:FONT_NUMBER];
    [mLabelGold setAnchorPoint:ccp(0, 0.5)];
    [mLabelGold setPosition:uniPos(ccp(mIconGold.position.x + 15, winSize.height - 22), ccp(mIconGold.position.x + 40, winSize.height - 44))];
    [self addChild:mLabelGold];
    
    // exit
    CCSprite *iconCancel = [CCSprite spriteWithSpriteFrameName:SFN_BACK];
    CCSprite *iconCancelHover = [CCSprite spriteWithSpriteFrameName:SFN_BACK];
    [iconCancelHover setColor:CL_BTN_INFO];

    CCMenuItemSprite *miExit = [CCMenuItemSprite itemWithNormalSprite:iconCancel selectedSprite:iconCancelHover target:self selector:@selector(onBack)];
    [miExit setPosition:uniPos(ccp(winSize.width - 20, winSize.height - 20), ccp(winSize.width - 40, winSize.height - 40))];
    miExit.activeArea = CGRectMake(-20, -20, miExit.contentSize.width + 40, miExit.contentSize.height + 40);
    [mMenu addChild:miExit];
}

-(void) initShop
{
    CGSize winSize = [[CCDirector sharedDirector] winSize];
    
    // layer item
    NSMutableArray *listLayer = [NSMutableArray array];
    for (int i = 0; i < 4; i++)
    {
        CCLayer *page = [CCLayer node];
        CCMenu *menu = [CCMenu menuWithArray:nil];
        [menu setPosition:CGPointZero];
        [page addChild:menu];
        
        CCSprite *panel = [CCSprite spriteWithSpriteFrameName:SFN_PANEL_2];
        [panel setPosition:uniPos(ccp(winSize.width / 2, winSize.height / 2), ccp(winSize.width / 2, winSize.height / 2))];
        [panel setColor:CL_PANEL_BG];
        [page addChild:panel];
        
        CCSprite *sprBuy = [CCSprite spriteWithSpriteFrameName:SFN_PANEL_2_BTN];
        CCSprite *sprBuyHover = [CCSprite spriteWithSpriteFrameName:SFN_PANEL_2_BTN];
        [sprBuy setColor:CL_PANEL_BG];
        [sprBuyHover setColor:CL_PANEL_BTN];
        CCMenuItem *miBuy = [CCMenuItemSprite itemWithNormalSprite:sprBuy
                                                       selectedSprite:sprBuyHover
                                                               target:self
                                                             selector:@selector(onBuy:)];
        [miBuy setTag:i];
        [miBuy setPosition:uniPos(ccp(winSize.width / 2, panel.position.y - 125), ccp(winSize.width / 2, panel.position.y - 251))];
        [menu addChild:miBuy];
        
        CCLabelBMFont *lbBuy = [[CCLabelBMFont alloc] initWithString:@"BUY" fntFile:FONT_DEFAULT];
        [lbBuy setAnchorPoint:ccp(0.5, 0.5)];
        [lbBuy setPosition:miBuy.position];
        [page addChild:lbBuy];
        
        CCSprite *sprIndicator = [[ItemInfo getInstance] getItemSprite:(ITEM_TYPE)i];
        [sprIndicator setPosition:uniPos(ccp(panel.position.x, panel.position.y + 60), ccp(panel.position.x, panel.position.y + 120))];
        [page addChild:sprIndicator];
        
        CCLabelBMFont *lbName = [CCLabelBMFont labelWithString:@"" fntFile:FONT_DEFAULT];
        [lbName setString:[[ItemInfo getInstance] getItemName:(ITEM_TYPE)i]];
        [lbName setAnchorPoint:ccp(0.5, 0.5)];
        [lbName setPosition:ccp(sprIndicator.position.x, uniPos(sprIndicator.position.y - 40, sprIndicator.position.y - 80))];
        [page addChild:lbName];
        
        CCLabelBMFont *lbDesc = [CCLabelBMFont labelWithString:@"" fntFile:FONT_DEFAULT];
        [lbDesc setString:[[ItemInfo getInstance] getItemDesc:(ITEM_TYPE)i]];
        [lbDesc setAnchorPoint:ccp(0., 0.5)];
        [lbDesc setWidth:uniPos(180, 360)];
        [lbDesc setPosition:uniPos(ccp(sprIndicator.position.x - 80, sprIndicator.position.y - 90), ccp(sprIndicator.position.x - 160, sprIndicator.position.y - 180))];
        [page addChild:lbDesc];
        
        CCLabelBMFont *lbPrice = [CCLabelBMFont labelWithString:@"" fntFile:FONT_DEFAULT];
        [lbPrice setString:[[ItemInfo getInstance] getItemPriceText:(ITEM_TYPE)i]];
        [lbPrice setAnchorPoint:ccp(0., 0.5)];
        [lbPrice setWidth:uniPos(200, 500)];
        [lbPrice setPosition:uniPos(ccp(sprIndicator.position.x - 80, sprIndicator.position.y - 150), ccp(sprIndicator.position.x - 160, sprIndicator.position.y - 300))];
        [page addChild:lbPrice];
        
        CCSprite *sprIconGold = [CCSprite spriteWithSpriteFrameName:SFN_ICON_GOLD];
        [sprIconGold setPosition:uniPos(ccp(lbPrice.position.x + lbPrice.contentSize.width + 15, lbPrice.position.y),
                                        ccp(lbPrice.position.x + lbPrice.contentSize.width + 30, lbPrice.position.y))];
        [page addChild:sprIconGold];
        
        [listLayer addObject:page];
    }
    
    mScrollLayerItem = [CCScrollLayer nodeWithLayers:listLayer widthOffset:uniPos(100, 300)];
    mScrollLayerItem.minimumTouchLengthToChangePage = 40;
    mScrollLayerItem.minimumTouchLengthToSlide = 10;
    mScrollLayerItem.marginOffset = winSize.width / 2;
    mScrollLayerItem.showPagesIndicator = YES;
    mScrollLayerItem.pagesIndicatorPosition = ccp(winSize.width / 2, uniPos(60, 120));
    
    [self addChild:mScrollLayerItem];
    
    
    // layer gold
    [listLayer removeAllObjects];
    for (int i = 0; i < 4; i++)
    {
        CCLayer *page = [CCLayer node];
        CCMenu *menu = [CCMenu menuWithArray:nil];
        [menu setPosition:CGPointZero];
        [page addChild:menu];
        
        CCSprite *panel = [CCSprite spriteWithSpriteFrameName:SFN_PANEL_2];
        [panel setPosition:ccp(winSize.width / 2, winSize.height / 2)];
        [panel setColor:CL_PANEL_BG];
        [page addChild:panel];
        
        CCSprite *sprBuy = [CCSprite spriteWithSpriteFrameName:SFN_PANEL_2_BTN];
        CCSprite *sprBuyHover = [CCSprite spriteWithSpriteFrameName:SFN_PANEL_2_BTN];
        [sprBuy setColor:CL_PANEL_BG];
        [sprBuyHover setColor:CL_PANEL_BTN];
        CCMenuItem *miBuy = [CCMenuItemSprite itemWithNormalSprite:sprBuy
                                                    selectedSprite:sprBuyHover
                                                            target:self
                                                          selector:@selector(onIAP:)];
        [miBuy setTag:i];
        [miBuy setPosition:uniPos(ccp(winSize.width / 2, panel.position.y - 125), ccp(winSize.width / 2, panel.position.y - 251))];
        [menu addChild:miBuy];
        
        CCLabelBMFont *lbBuy = [[CCLabelBMFont alloc] initWithString:@"BUY" fntFile:FONT_DEFAULT];
        [lbBuy setAnchorPoint:ccp(0.5, 0.5)];
        [lbBuy setPosition:miBuy.position];
        [page addChild:lbBuy];
        
        CCSprite *sprIndicator = [[ItemInfo getInstance] getPacketSprite:(IAP_TYPE)i];
        [sprIndicator setPosition:uniPos(ccp(panel.position.x, panel.position.y + 60), ccp(panel.position.x, panel.position.y + 120))];
        [page addChild:sprIndicator];
        
        CCLabelBMFont *lbName = [CCLabelBMFont labelWithString:@"" fntFile:FONT_DEFAULT];
        [lbName setString:[[ItemInfo getInstance] getPacketName:(IAP_TYPE)i]];
        [lbName setAnchorPoint:ccp(0.5, 0.5)];
        [lbName setPosition:ccp(sprIndicator.position.x, uniPos(sprIndicator.position.y - 40, sprIndicator.position.y - 80))];
        [page addChild:lbName];
        
        CCLabelBMFont *lbDesc = [CCLabelBMFont labelWithString:@"" fntFile:FONT_DEFAULT];
        [lbDesc setString:[[ItemInfo getInstance] getPacketDesc:(IAP_TYPE)i]];
        [lbDesc setAnchorPoint:ccp(0., 0.5)];
        [lbDesc setWidth:uniPos(200, 500)];
        [lbDesc setPosition:uniPos(ccp(sprIndicator.position.x - 80, sprIndicator.position.y - 90), ccp(sprIndicator.position.x - 160, sprIndicator.position.y - 180))];
        [page addChild:lbDesc];
        
        CCLabelBMFont *lbPrice = [CCLabelBMFont labelWithString:@"" fntFile:FONT_DEFAULT];
        [lbPrice setString:[[ItemInfo getInstance] getPacketPriceText:(IAP_TYPE)i]];
        [lbPrice setAnchorPoint:ccp(0., 0.5)];
        [lbPrice setWidth:uniPos(200, 500)];
        [lbPrice setPosition:uniPos(ccp(sprIndicator.position.x - 80, sprIndicator.position.y - 150), ccp(sprIndicator.position.x - 160, sprIndicator.position.y - 300))];
        [page addChild:lbPrice];
        
        CCSprite *sprIconGold = [CCSprite spriteWithSpriteFrameName:SFN_ICON_GOLD];
        [sprIconGold setPosition:uniPos(ccp(lbDesc.position.x + lbDesc.contentSize.width + 15, lbDesc.position.y),
                                        ccp(lbDesc.position.x + lbDesc.contentSize.width + 30, lbDesc.position.y))];
        [page addChild:sprIconGold];
        
        [listLayer addObject:page];
    }
    
    mScrollLayerGold = [CCScrollLayer nodeWithLayers:listLayer widthOffset:uniPos(100, 300)];
    mScrollLayerGold.minimumTouchLengthToChangePage = 40;
    mScrollLayerGold.minimumTouchLengthToSlide = 10;
    mScrollLayerGold.marginOffset = winSize.width / 2;
    mScrollLayerGold.showPagesIndicator = YES;
    mScrollLayerGold.pagesIndicatorPosition = ccp(winSize.width / 2, uniPos(60, 120));

    
    [self addChild:mScrollLayerGold];
    [mScrollLayerGold setVisible:NO];
    [mScrollLayerGold setTouchEnabled:NO];
}

-(void) initTwoLine
{
    CGSize winSize = [[CCDirector sharedDirector] winSize];
    CCSprite *spr = [CCSprite spriteWithSpriteFrameName:SFN_THICK_LINE];
    [spr setPosition:uniPos(ccp(winSize.width / 2, 40), ccp(winSize.width / 2, 80))];
    [self addChild:spr];
    
    CCSprite *spr2 = [CCSprite spriteWithSpriteFrameName:SFN_THICK_LINE];
    [spr2 setPosition:uniPos(ccp(winSize.width / 2, winSize.height - 40), ccp(winSize.width / 2, winSize.height - 80))];
    [self addChild:spr2];
}

-(void) initItem
{
    mMIItemGlove = [[[ItemIcon alloc] initWithType:eIT_SHIELD] autorelease];
    mMIItemXRay = [[[ItemIcon alloc] initWithType:eIT_XRAY] autorelease];
    mMIItemTimer = [[[ItemIcon alloc] initWithType:eIT_TIMER] autorelease];
    mMIItemMagnet = [[[ItemIcon alloc] initWithType:eIT_MAGNET] autorelease];
    
    [self addChild:mMIItemGlove z:0 tag:0];
    [self addChild:mMIItemXRay z:0 tag:1];
    [self addChild:mMIItemTimer z:0 tag:2];
    [self addChild:mMIItemMagnet z:0 tag:3];
    
    CGSize winSize = [[CCDirector sharedDirector] winSize];
    float anchorX = (winSize.width - 20) / 4;
    int count = 1;
    int paddleX = uniPos(-40, -80);
    int baseY = 22;
    float baseX;
    for (int i = 0; i < 4; i++)
    {
        baseX = count * anchorX + paddleX;
        ItemIcon *menuItem = (ItemIcon *)[self getChildByTag:i];
        [menuItem showNumItemUse:NO];
        [menuItem setPosition:uniPos(ccp(baseX, baseY), ccp(baseX, baseY * 2))];
        
        count++;
    }
}

-(void) onTabItem
{
    [[Utility getInstance] playEffect:SOUND_MENU_BUTTON];
    [mTabGold unselected];
    [mTabGold setIsEnabledWithoutUpdate:YES];
    [mTabItem selected];
    [mTabItem setIsEnabledWithoutUpdate:NO];
    [mScrollLayerGold setVisible:NO];
    [mScrollLayerGold setTouchEnabled:NO];
    [mScrollLayerItem setVisible:YES];
    [mScrollLayerItem setTouchEnabled:YES];
}

-(void) onTabGold
{
    [[Utility getInstance] playEffect:SOUND_MENU_BUTTON];
    [mTabItem unselected];
    [mTabItem setIsEnabledWithoutUpdate:YES];
    [mTabGold selected];
    [mTabGold setIsEnabledWithoutUpdate:NO];
    [mScrollLayerGold setVisible:YES];
    [mScrollLayerGold setTouchEnabled:YES];
    [mScrollLayerItem setVisible:NO];
    [mScrollLayerItem setTouchEnabled:NO];
}

-(void) onBack
{
    [[Utility getInstance] playEffect:SOUND_MENU_BUTTON];
    if ([MainGameScene getInstance] != nil)
    {
        [[MainGameScene getInstance]._mainGameUI updateItemInfo];
        [MainGameScene getInstance]._isShopJustClose = YES;
    }
    [[CCDirector sharedDirector] popScene];
}

-(void) onIAP:(NSObject *)sender
{
    [[Utility getInstance] playEffect:SOUND_MENU_BUTTON];
    CCLOG(@"onBuy");
    CCMenuItem *item = (CCMenuItem *)sender;
    IAP_TYPE type = (IAP_TYPE)item.tag;
    
    [[GameIAP getInstance] buyPacket:type];
}

-(void) onBuy:(NSObject *)sender
{
    [[Utility getInstance] playEffect:SOUND_MENU_BUTTON];
    CCLOG(@"onBuy");
    CCMenuItem *item = (CCMenuItem *)sender;
    ITEM_TYPE type = (ITEM_TYPE)item.tag;
    
    int price = [[ItemInfo getInstance] getItemPrice:type];
    if ([UserInfo getInstance]._userGold < price)
    {
        CCScaleTo *scaleTo = [CCScaleTo actionWithDuration:0.5 scale:1.5];
        CCTintTo *tintTo = [CCTintTo actionWithDuration:0.5 red:255 green:0 blue:0];
        CCSpawn *spawn = [CCSpawn actions:scaleTo, tintTo, nil];
        CCScaleTo *scaleTo2 = [CCScaleTo actionWithDuration:0.5 scale:1];
        CCTintTo *tintTo2 = [CCTintTo actionWithDuration:0.5 red:255 green:255 blue:255];
        CCSpawn *spawn2 = [CCSpawn actions:scaleTo2, tintTo2, nil];
        CCSequence *sequence = [CCSequence actions:spawn, spawn2, nil];
        [mIconGold runAction:sequence];
        return;
    }
    
    if (type == eIT_SHIELD)
    {
        [UserInfo getInstance]._numItemGlove++;
    }
    else if (type == eIT_TIMER)
    {
        [UserInfo getInstance]._numItemTime++;
    }
    else if (type == eIT_XRAY)
    {
        [UserInfo getInstance]._numItemXray++;
    }
    else if (type == eIT_MAGNET)
    {
        [UserInfo getInstance]._numItemMagnet++;
    }
    
    mIncrease = -1;
    mGoldShow = [UserInfo getInstance]._userGold;
    
    [UserInfo getInstance]._userGold -= price;
    [[UserInfo getInstance] saveUserInfo];
    
    [self updateUserInfo];
    [[NSNotificationCenter defaultCenter] postNotificationName:EVENT_GOLD_CHANGED object:nil];
}

-(void) updateUserInfo
{
    [mMIItemGlove updateLabel];
    [mMIItemMagnet updateLabel];
    [mMIItemTimer updateLabel];
    [mMIItemXRay updateLabel];
}

-(void) updateLabelGold
{
    [mLabelGold setString:[NSString stringWithFormat:@"%lld", [UserInfo getInstance]._userGold]];
}

-(void) updateGoldNextGold
{
    [[Utility getInstance] playEffect:SOUND_GOLD];
    numGoldChange = mGoldShow - [UserInfo getInstance]._userGold;
    mIncrease = numGoldChange > 0 ? -1 : 1;
    numGoldChange = abs(numGoldChange) * 2;
    
    [self unschedule:@selector(updateGoldAnim:)];
    [self schedule:@selector(updateGoldAnim:)];
}


-(void) updateGoldAnim:(ccTime)delta
{
    mGoldShow += numGoldChange * delta * mIncrease;
    if (mGoldShow * mIncrease >= [UserInfo getInstance]._userGold * mIncrease)
    {
        mGoldShow = [UserInfo getInstance]._userGold;
        [self unschedule:_cmd];
    }
    
    NSString *strTime = [NSString stringWithFormat:@"%d", (int)(mGoldShow)];
    [mLabelGold setString:strTime];
}


-(void) dealloc
{
    CCLOG(@"shop dealloc!");
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

@end
